package org.ahead4.joint.common;

import org.ahead4.joint.dto.RequestEnvelope;
import org.ahead4.joint.dto.ResponseEnvelope;
import org.ahead4.joint.utils.OkHttpUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 对接工具
 * @author WangYu
 * @title: JointUtils
 * @description: TODO
 * @date 2020/3/1413:41
 */
public class JointUtils {
    private static final Log logger = LogFactory.getLog(JointUtils.class);

    public static void send(String url, RequestEnvelope requestEnvelope) {
        try {
            ResponseEnvelope responseEnvelope = ResponseEnvelope.parse(OkHttpUtils.syncPostJSON(url, requestEnvelope.toJSONString()));
            if (!responseEnvelope.isSuccessful()) {
                String message = "code:" + responseEnvelope.getCode() + ";message:" + responseEnvelope.getMsg();
                logger.error(message);
                throw new RuntimeException(message);
            }
        } catch (Exception e) {
            // TODO 出现异常时应该有对应重发机制
            e.printStackTrace();
            ResponseEnvelope responseEnvelope = null;
            /**
             * 重发三次
             */
            for (int i = 0; i < 3; i++) {
                try {
                    responseEnvelope = ResponseEnvelope.parse(OkHttpUtils.syncPostJSON(url, requestEnvelope.toJSONString()));
                    if (!responseEnvelope.isSuccessful()) {
                        String message = "code:" + responseEnvelope.getCode() + ";message:" + responseEnvelope.getMsg();
                        throw new Exception(message);
                    } else {
                        break;
                    }
                } catch (Exception retryE) {
                    logger.error(retryE);
                }
            }
            logger.error(new StringBuilder("\n")
                    .append(url).append("重发三次失败\n")
                    .append("RequestEnvelope:").append(requestEnvelope.toJSONString()).append("\n")
                    .append("ResponseEnvelope:").append(responseEnvelope==null? null : responseEnvelope.toJSONString()).append("\n")
            );
        }
    }
}
